<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <meta name="viewport" content="width=device-width,initial-scale=1"/>
    <!-- 导入boot文件，顺序固定	 -->
    <link rel="stylesheet" href="../css/bootstrap.css">
    <script src="../js/jquery.min.js"></script>
    <script src="../js/popper.min.js"></script>
    <script src="../js/bootstrap.min.js"></script>
    <script src="../js/vue.js"></script>
    <link rel="stylesheet" href="../css/comm.css"/>
    <link rel="stylesheet" href="../css/detail.css"/>
    <style>
        /* 评论输入框样式 */
        .comment-input {
            border: none;
            border-bottom: 1px solid #ccc;
            padding: 5px;
            width: 100%;
            font-size: 14px;
        }
        
        /* 发布按钮样式 */
        .comment-button {
            display: inline-block;
            padding: 5px 10px;
            background-color: #4CAF50; /* 绿色 */
            border: none;
            border-radius: 4px;
            color: white;
            text-align: center;
            text-decoration: none;
            font-size: 14px;
            margin: 4px 2px;
            cursor: pointer;
            transition: background-color 0.3s; /* 动画效果 */
        }
        
        /* 鼠标悬停在发布按钮上时改变背景色 */
        .comment-button:hover {
            background-color: #45a049; /* 深一点的绿色 */
        }
        
        /* 评论列表样式 */
        .comment-list {
            list-style-type: none;
            padding: 0;
        }
        
        .comment-item {
            margin-bottom: 10px;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 4px;
            background-color: #f8f9fa; /* 淡灰色背景 */
        }
        
        .comment-content {
            font-size: 14px;
        }
        
        .comment-author-date {
            font-size: 12px;
            color: #777;
        }
    </style>
</head>

<body>
<header>
    <iframe src="header.html" frameborder="0" class="my_header" scrolling="no"></iframe>
</header>
<div id="app">
    <div class="container">
        <div class="row mt-5">
            <div class="col-md-1 col-sm-10">
                <div class="w-50 ">
                   
                </div>
               
            </div>
            <div class="col-md-10 col-sm-12 py-2">
                <h3>{{plants.title}}</h3>
                <div class="small my_gray border-bottom pb-2">
                    <span class="text-success">{{plants.posted_date}}</span>
                    <span>投稿：{{author_name}}</span>
                    <span>阅读（<span>{{plants.read_count}}</span>）</span>
                </div >
                <div class="p-4" >
                   <p v-html="plants.description"></p>
                </div>
                <div class="w-100 bg-secondary text-center text-white
                py-2">
                    
                </div>
                <div class="w-100 text-center pt-4" >
                    <button class="my_green border-0" @click="userLike">{{like}}</button>
                </div>
                <div class="d-flex justify-content-around small py-2">
                    <a href="javascript:;" @click="toPreOrNext(pre.id)" >
                        <p v-show="!pre.title==''">上一篇 <br/>{{pre.title}}</p>
                    </a>
                    <a href="javascript:;" @click="toPreOrNext(next.id)">
                        <p v-show="!next.title==''">下一篇 <br/>
                            {{next.title}}
                        </p>
                    </a>
                </div>

               <!-- 评论输入框和发布按钮 -->
                <div class="col-lg-5 col-sm-0 p-0 pt-4">
                    <input type="text" placeholder="发布评论" class="comment-input" v-model="content"/>
                    <a href="javascript:;" class="comment-button" @click="addComment">发布</a>
                </div>

                <!-- 评论列表 -->
                <ul class="comment-list">
                    <li v-for="comment in comments" class="comment-item">
                        <p class="comment-content">{{ comment.content }}</p>
                        <p class="comment-author-date">{{ comment.user_id }} - {{ comment.create_time }}
                            <button 
                                style="margin-left:  10em;" 
                                class="btn btn-info" 
                                @click="deleteComments(comment.id)"
                                v-if="userId==plants.author_id">删除</button>
                        </p>
                        
                    </li>
                </ul>
                <div>
                    
                </div>

            </div>
        </div>
        <!-- 最下方-->
        <div class="row my-4">
            <div class="text-center w-100">
                Copright&nbsp;&copy;&nbsp;2012-2015&nbsp;岁草SUICAO.COM
            </div>
        </div>
    
    </div>
</div>
</body>
<script>
    new Vue({
        el: "#app",
        data: {
           plants:{
                description: // 富文本的文章详情
                `
                    <p style="margin:5px auto;"><p style="margin:5px auto;font-size:1.5vh;">今天是一个美好的日子。阳光明媚，微风轻拂。我决定漫步在公园里，欣赏大自然的美丽。树木婆娑，花儿绽放，仿佛整个世界都沉浸在宁静中。在湖边坐下，闭上眼睛，感受微风拂过脸庞的温暖。这一刻，心灵得到了安宁，仿佛所有烦恼都被风吹散了。</p></p>
                `,
                author_id:"",//作者id
                image_path:"",// 文章图片地址
                like_count:"",// 喜欢的总人数
                plant_id:"",// 文章id
                posted_date:"", // 发布时间
                read_count:"",// 阅读总数
                title:"", // 标题
           },
           like:"点赞",
           userId:"",
           id:"",// url中的ID
           author_name:"",// 作者名
           next:{// 下一个文章的标题和id
                title:"",
                id:""
           },
           pre:{// 上一个文章的标题的id
                title:"",
                id:""
           },
           comments:[
              
            ],//评论表
            content:""//评论的内容
        
        },
        //网页一进来就调用
        async created() {
            await this.getLoginId()
            await this.getIdFromUrl()// 从url获取id
            await this.getDetail()// 获取详情
            await this.getUserInfo()// 获取作者详情
            await this.getNext()// 获取上一篇文章
            await this.getPre()// 获取下一篇文章
            await this.isLike()// 判断是否点赞
            await this.addReadNumber()// 阅读量+1
            await this.getComments() // 获取评论
        },
        // 方法全部写在这
        methods:{
            //获取登录的id
            getLoginId(){
                this.userId = sessionStorage.getItem("id")
            },
            // 阅读量+1
            async addReadNumber(){
                const response = await fetch('http://localhost:5000/plants/addRead?id='+this.id);
                const data = await response.json();
            },
            // 获取评论
            async getComments(){
                const response = await fetch('http://localhost:5000/comment/getCommentByPlantId?plantId='+this.id);
                const data = await response.json();
                if(data.code == 200){
                    // 赋值到文章详情的对象
                    this.comments = data.data
                }
            },
            // 从url获取id
            getIdFromUrl() {  
                const searchParams = new URLSearchParams(window.location.search);  
                this.id = searchParams.get('id');  
            },
            // 通过文章id获取详情
            async getDetail(){
                const response = await fetch('http://localhost:5000/plants/getPlantsById?id='+this.id);
                const data = await response.json();
                if(data.code == 200){
                    // 赋值到文章详情的对象
                    this.plants = data.data[0]
                }
            },
            // 通过用户id获取用户信息
            async getUserInfo(){
                console.log(this.plants.author_id);
                const response = await fetch('http://localhost:5000/user/getUserInfoById?id='+this.plants.author_id);
                const data = await response.json();
                // 主要是获取用户名
                this.author_name = data.data[0].nick_name;
            },
            //判断是否点赞
            async isLike(){
                if(this.userId!=null&&this.userId!=""){
                    const response = await fetch('http://localhost:5000/plants/isLike?id='+this.id+'&userId='+this.userId);
                    const data = await response.json()
                    if(data.code == 500){
                        this.like = "点赞"
                    }else{
                        this.like = "已点赞"
                    }
                }
            },
            // 点赞
            async userLike(){
                if(this.userId!=null&&this.userId!=""){
                    const response = await fetch('http://127.0.0.1:5000/plants/like?id='+this.id+'&userId='+this.userId);
                    const data = await response.json()
                    if(data.code == 200){
                        alert("成功")
                        window.location.reload()
                    }
                }else{
                    alert("请登录")
                }
            },
            // 下一篇
            async getNext(){
                const response = await fetch('http://127.0.0.1:5000/plants/getNext?id='+this.id);
                const data = await response.json()
                if(data.code == 200){
                    // 下一篇的标题的id
                    this.next.title = data.data.title
                    this.next.id = data.data.plant_id
                }
            },
             //删除评论
             async deleteComments(commentId){
                const response = await fetch('http://localhost:5000/comment/delete?id='+commentId);
                    const data = await response.json()
                    if(data.code == 200){
                       alert("删除成功")
                    }
                    this.getComments()
            },
            //发布评论
            async addComment(){
                if(this.userId!=null&&this.userId!=""){
                    // 登录的json数据
                    const jsonData = {
                        "userId":sessionStorage.getItem("id"),
                        "content":this.content,
                        "plantId":this.id
                    }
                    const response = await fetch('http://localhost:5000/comment/add',{
                        method: 'POST', // 指定请求方法为POST  
                        headers: {  
                            'Content-Type': 'application/json', // 设置请求头，指定发送的数据类型为JSON  
                        }, 
                        body: JSON.stringify(jsonData), // 将JavaScript对象转换为JSON字符串作为请求体发送
                    });
                    // post
                    const data =await response.json()
                    // 请求成功
                    if(data.code == 200){
                        alert("评论成功")
                        this.content = ""
                        this.getComments()
                    }
                }else{
                    alert("请登录")
                }
               
            },
            // 上一篇
            async getPre(){
                const response = await fetch('http://127.0.0.1:5000/plants/getPre?id='+this.id);
                const data = await response.json()
                if(data.code == 200){
                    // 上一篇的标题的id
                    this.pre.title = data.data.title
                    this.pre.id = data.data.plant_id
                }else{

                }
                
            },
            // 跳转
            toPreOrNext(opt){
                // 直接跳转到指定id的文章（这里是上一篇和下一篇的功能）
                window.location.href = "/html/detail.html?id="+opt
            }
        },
       
     })
</script>
</html>